var mongoose = exports.mongoose = require('mongoose');
var db = exports.db = mongoose.createConnection();
var ObjectId = exports.ObjectId = mongoose.Types.ObjectId;

var settings = require("../config/settings");

var options = {
    db: { native_parser: true },
    server: { poolSize: settings.mongodb_poolSize },
    user: settings.mongodb_user,
    pass: settings.mongodb_pass
};

console.log(options);
exports.openDB = function() {
    db.open(settings.mongodb_host, settings.mongodb_db, settings.mongodb_port, options);
    console.log("open db");
};


db.on('error', function(err) {
    console.error("db error");
    db.close();
});


//监听db close event并重新连接
db.on('close', function() {
    console.log("db closed");
    db.open(settings.mongodb_host, settings.mongodb_db, settings.mongodb_port, options);
    console.log("db reopen");
});

db.on("connected", function(err) {
    if (err) {
        console.log("db connect failed !");
    } else {
        console.log("db connect success !");
    }
});
